package com.writing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.writing.entity.WritingGoal;
import com.writing.mapper.WritingGoalMapper;
import com.writing.service.WritingGoalService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 写作目标服务实现类
 */
@Service
@RequiredArgsConstructor
public class WritingGoalServiceImpl extends ServiceImpl<WritingGoalMapper, WritingGoal> implements WritingGoalService {

    @Override
    public List<WritingGoal> getGoalsByUserId(Long userId) {
        return this.list(new LambdaQueryWrapper<WritingGoal>()
                .eq(WritingGoal::getUserId, userId)
                .orderByDesc(WritingGoal::getCreatedAt));
    }

    @Override
    public WritingGoal getGoalById(Long goalId, Long userId) {
        return this.getOne(new LambdaQueryWrapper<WritingGoal>()
                .eq(WritingGoal::getId, goalId)
                .eq(WritingGoal::getUserId, userId));
    }

    @Override
    public WritingGoal createGoal(WritingGoal goal) {
        // 设置默认值
        if (goal.getCurrentValue() == null) {
            goal.setCurrentValue(0);
        }
        if (goal.getStatus() == null) {
            goal.setStatus("active");
        }
        if (goal.getUnit() == null) {
            goal.setUnit("words");
        }
        if (goal.getPriority() == null) {
            goal.setPriority(0);
        }
        if (goal.getProgressHistory() == null) {
            goal.setProgressHistory(new ArrayList<>());
        }
        
        this.save(goal);
        return goal;
    }

    @Override
    public WritingGoal updateGoal(WritingGoal goal) {
        this.updateById(goal);
        return goal;
    }

    @Override
    public WritingGoal updateProgress(Long goalId, Long userId, Integer increment, String note) {
        WritingGoal goal = getGoalById(goalId, userId);
        if (goal == null) {
            throw new RuntimeException("目标不存在或无权限访问");
        }
        
        // 更新当前进度
        goal.setCurrentValue(goal.getCurrentValue() + increment);
        
        // 添加进度历史记录
        List<Map<String, Object>> progressHistory = goal.getProgressHistory();
        if (progressHistory == null) {
            progressHistory = new ArrayList<>();
        }
        
        Map<String, Object> progressRecord = new HashMap<>();
        progressRecord.put("id", System.currentTimeMillis());
        progressRecord.put("date", LocalDateTime.now().toString());
        progressRecord.put("increment", increment);
        progressRecord.put("note", note);
        
        progressHistory.add(0, progressRecord); // 添加到开头
        goal.setProgressHistory(progressHistory);
        
        // 检查是否完成目标
        if (goal.getCurrentValue() >= goal.getTargetValue()) {
            goal.setStatus("completed");
        }
        
        this.updateById(goal);
        return goal;
    }

    @Override
    public boolean deleteGoal(Long goalId, Long userId) {
        WritingGoal goal = getGoalById(goalId, userId);
        if (goal == null) {
            return false;
        }
        return this.removeById(goalId);
    }

    @Override
    public long getActiveGoalsCount(Long userId) {
        return this.count(new LambdaQueryWrapper<WritingGoal>()
                .eq(WritingGoal::getUserId, userId)
                .eq(WritingGoal::getStatus, "active"));
    }

    @Override
    public long getCompletedGoalsCount(Long userId) {
        return this.count(new LambdaQueryWrapper<WritingGoal>()
                .eq(WritingGoal::getUserId, userId)
                .eq(WritingGoal::getStatus, "completed"));
    }
}
